package cn.tedu.luban.worker.webapi.utils;

import cn.tedu.luban.commons.exception.LubanServiceException;
import cn.tedu.luban.commons.pojo.domain.UserAuthenticationInfo;
import cn.tedu.luban.commons.pojo.ums.model.User;
import cn.tedu.luban.commons.restful.ResponseCode;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import sun.net.www.protocol.http.AuthenticationInfo;

public class SecurityContext {

    public static UserAuthenticationInfo getUserInfo(){
        // 获取SpringSecurity上下文对象
        UsernamePasswordAuthenticationToken token=
                (UsernamePasswordAuthenticationToken)
                        SecurityContextHolder.getContext().getAuthentication();
        // 为了程序逻辑严谨,判断一下token是否为null
        if(token == null){
            throw new LubanServiceException(
                    ResponseCode.UNAUTHORIZED,"您还没有登录");
        }
        // 从SpringSecurity上下文对象中获取用户信息
        UserAuthenticationInfo userInfo=
                (UserAuthenticationInfo) token.getCredentials();
        // 最终返回用户信息
        return userInfo;
    }
    public static Long getUserId(){
        return getUserInfo().getId();
    }
}
